﻿using HMS.Contracts.Models;
using HMS.TenantServer.Abstractions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace HMS.TenantServer.Controllers;

[Route("[controller]")]
[ApiController]
public class TenantController : ControllerBase
{
    private readonly ITenantManager _service;

    public TenantController(ITenantManager service)
    {
        _service = service;
    }

    [HttpGet("register")]
    public async Task<IActionResult> RegisterAsync([FromQuery] string name)
    {
        var result = await _service.RegisterAsync(name, HttpContext.RequestAborted);

        return Ok(result);
    }

    [HttpGet("register_user")]
    public async Task<IActionResult> RegisterUserAsync([FromQuery] RegisterUser user)
    {
        var result = await _service.RegisterUserAsync(user.Name, user.TenantId, HttpContext.RequestAborted);

        return Ok(result);
    }

    [HttpGet("get_user")]
    [Authorize("Root")]
    public async Task<IActionResult> GetUserListAsync()
    {
        var tenantId = User.FindFirstValue("tenant");

        return !string.IsNullOrEmpty(tenantId)
            ? Ok(await _service.GetUsersAsync(tenantId, HttpContext.RequestAborted))
            : BadRequest("未识别到租户ID");
    }

    [HttpGet("get_tenant")]
    [Authorize("Ultimate")]
    public async Task<IActionResult> GetTenantListAsync()
    {
        var result = await _service.GetTenantsAsync();

        return Ok(result);
    }
}